//处理tree数据结构
export function formatTreeData (data, level = 1,showRename=false){
  return data.map(item => {
    const newItem = { ...item, level, showRename }; // 添加 level 属性
    if (newItem.children && newItem.children.length > 0) {
      newItem.children = formatTreeData(newItem.children, level + 1,false); // 递归处理子节点
    }
    return newItem;
  });
}
//根据status过滤tree数据
export function processTreeByStatus(tree, status) {
  let result = [];

  function processNode(node, targetStatus) {
    if (node.mustLearnStatus == targetStatus && node.type == 3) {
      result.push(node);
    }
    if (node.children) {
      node.children.forEach(child => {
        processNode(child, targetStatus);
      });
    }
  }

  tree.forEach(node => {
    processNode(node, status);
  });

  return result;
}

//处理 任务分类后的tree数据结构
export function processTree(tree, mastData, chooseData) {
  function findAndProcessNode(node) {
    if (node.type == 3) {
      if (mastData.some(item => item.id === node.id)) {
        node.mustLearnStatus = 1;
      } else if (chooseData.some(item => item.id === node.id)) {
        node.mustLearnStatus = 2;
      }
    }
    if (node.children) {
      node.children.forEach(child => {
        findAndProcessNode(child);
      });
    }
  }

  tree.forEach(node => {
    findAndProcessNode(node);
  });

  return tree;
}

//添加数据至tree数据里
export function  addToChildren(arr, parentId, newObj) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].id === parentId) {
      if (!arr[i].children) {
        arr[i].children = [];
      }
      arr[i].children.push(newObj);
      return true;
    } else if (arr[i].children) {
      if (addToChildren(arr[i].children, parentId, newObj)) {
        return true;
      }
    }
  }
  return false;
}
//删除tree数据 arr整颗树
export function removeItemById(arr, id) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].id === id) {
      arr.splice(i, 1);
      return true;
    } else if (arr[i].children) {
      if (removeItemById(arr[i].children, id)) {
        return true;
      }
    }
  }
  return false;
}
